package com.myspace.service.impl.record;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.myspace.mapper.RecordMapper;
import com.myspace.mapper.UserMapper;
import com.myspace.pojo.Record;
import com.myspace.pojo.User;
import com.myspace.service.space.record.RemoveRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RemoveRecordServiceImpl implements RemoveRecordService {
    @Autowired
    private RecordMapper recordMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Map<String, String> removerecord(Integer followId, Integer targetId) {
        QueryWrapper<Record> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("follow_id", followId);
        List<Record> records = recordMapper.selectList(queryWrapper);

        User user = userMapper.selectById(targetId);

        Map<String, String> map = new HashMap<>();
        for (Record record: records) {
            if(targetId.equals(record.getTargetId())) {
                user.setFollowerCount(Math.max(user.getFollowerCount() - 1, 0));
                userMapper.updateById(user);
                recordMapper.deleteById(record.getId());
                map.put("error_message", "success");
                return map;
            }
        }

        map.put("error_message", "failed");
        return map;
    }
}
